<?php

class CreativesController extends Controller
{
	/**
	 * @var string the default layout for the views. Defaults to '//layouts/column2', meaning
	 * using two-column layout. See 'protected/views/layouts/column2.php'.
	 */
	public $layout='//layouts/column2';

	/**
	 * @return array action filters
	 */
	public function filters()
	{
		return array(
			'accessControl', // perform access control for CRUD operations
		);
	}

	/**
	 * Specifies the access control rules.
	 * This method is used by the 'accessControl' filter.
	 * @return array access control rules
	 */
	public function accessRules()
	{
		return array(
			array('allow',  // allow all users to perform 'index' and 'view' actions
				'actions'=>array('index','view'),
				'users'=>array('*'),
			),
			array('allow', // allow authenticated user to perform 'create' and 'update' actions
				'actions'=>array('create','update', 'AddFavCrea', 'AddFavUsr', 'IndexFavCrea', 'IndexFavUsr', 'DelFavUsr', 'DelFavCrea', 'indexallfav', 'IsFavCrea', 'IsFavUsr', 'AllContentsPoints', 'ActualContentInfos', 'Private'),
				'users'=>array('@'),
			),
			array('allow', // allow admin user to perform 'admin' and 'delete' actions
				'actions'=>array('admin','delete'),
				'users'=>array('admin'),
			),
			array('deny',  // deny all users
				'users'=>array('*'),
			),
		);
	}

	/**
	 * Displays a particular model.
	 * @param integer $id the ID of the model to be displayed
	 */
	public function actionView($id)
	{
		$condition = "";
		$dataProvider=new CActiveDataProvider('ContentTypes', array(
			'criteria'=>array(
			'condition'=>$condition,
			'order'=>'rand()',
			),
			'pagination' => array('pageSize' => 4,),
			'totalItemCount' => 4,
		));
		

		$this->render('view',array(
			'model'=>$this->loadModel($id),
			'dataprovider'=>$dataProvider,
		));
	}
	
	public function actionPrivate($id)
	{
	
		$dataProvider = new CActiveDataProvider('Contents', array(
        'pagination'=>array(
             'pageSize'=>10,
        ),
		));
	
		$model=User::model()->findByPk((int)$id);
	
		$this->render('private',array(
			'model'=>$model,
			'dataprovider'=>$dataProvider,
		));
	
	}
	

	/**
	 * Creates a new model.
	 * If creation is successful, the browser will be redirected to the 'view' page.
	 */
	public function actionCreate()
	{
		$model=new Creatives;

		// Uncomment the following line if AJAX validation is needed
		$this->performAjaxValidation($model);

		if(isset($_POST['Creatives']))
		{
			$uid=Yii::app()->user->id;
			$model->attributes=$_POST['Creatives'];
			$model->date=new CDbExpression('NOW()');
			
			preg_match('/src=.*..jpg/', $model->content, $matches);
			$matches= str_replace ('src="', '', $matches);
			print_r($matches);
			if ($matches != null)
			{
				foreach ($matches as &$value) {
						$value = $value.';';
				}
				$model->pictures_path=$value;
			}

			if($model->save())
			{
				// init and add points
				$points = SiteController::actionInitPoints($model->id, 'content', 'Creatives');
				$upoints = SiteController::actionAddPoints('create_creative', 'Creatives', "$model->id", "$model->type");	
				$this->redirect(array('view','id'=>$model->id));
			}
		}
		
		$modele=new Events;
		
		// Uncomment the following line if AJAX validation is needed
		$this->performAjaxValidation($modele);

		if(isset($_POST['Events']))
		{
			$modele->attributes=$_POST['Events'];
			$modele->create_date=new CDbExpression('NOW()');
			if($modele->save())
				$this->redirect(array('events/view','id'=>$modele->id));
		}

		
		$modelk=new Knowledge;

		// Uncomment the following line if AJAX validation is needed
		$this->performAjaxValidation($modelk);
		
		$uid=Yii::app()->user->id;
		if(isset($_POST['Knowledge']))
		{
			$modelk->attributes=$_POST['Knowledge'];
			$modelk->date=new CDbExpression('NOW()');
			$modelk->creator_id=$uid;
			if($modelk->save())
				$this->redirect(array('knowledge/view','id'=>$modelk->id));
		}
		
		$models=new Swaps;

		// Uncomment the following line if AJAX validation is needed
		 $this->performAjaxValidation($models);

		if(isset($_POST['Swaps']))
		{
			$models->attributes=$_POST['Swaps'];
			$models->date=new CDbExpression('NOW()');
			$models->creator_id=$uid;
			
			$image=CUploadedFile::getInstance($models,'pictures_path');
			$image_dir = '/files/';
			$image_filename = round(microtime(true) * 1000) . '.jpg';
			$models->pictures_path = $image_dir . $image_filename;

			if($models->save()){
				if (!file_exists($image_dir))
					mkdir($image_dir);
				
				$image->saveAs($models->pictures_path);
				
				$this->redirect(array('swaps/view','id'=>$models->id));
				}
		}
		
		$this->render('create',array(
			'model'=>$model,
			'modele'=>$modele,
			'modelk'=>$modelk,
			'models'=>$models,
		));

	}

	/**
	 * Updates a particular model.
	 * If update is successful, the browser will be redirected to the 'view' page.
	 * @param integer $id the ID of the model to be updated
	 */
	public function actionIsFavCrea($id)
	{
		$uid=Yii::app()->user->id;
		
		$sql = "select * from fav_creatives where id=$id AND user_id=$uid"; 
				$command = Yii::app()->db->createCommand($sql);   
				$data=$command->queryAll();	
		
		if ($data == null)
		{
			return 0;
		}
		else
		{
			return 1;
		}
	}
	
	public function actionIsFavUsr($id)
	{
		$uid=Yii::app()->user->id;
		
		$sql = "select * from fav_users where user_id=$uid AND subuser_id=$id"; 
				$command = Yii::app()->db->createCommand($sql);   
				$data=$command->queryAll();	
		
		if ($data == null)
		{
			return 0;
		}
		else
		{
			return 1;
		}
	}

	
	public function actionUpdate($id)
	{
		$model=$this->loadModel($id);

		// Uncomment the following line if AJAX validation is needed
		// $this->performAjaxValidation($model);

		if(isset($_POST['Creatives']))
		{
			$model->attributes=$_POST['Creatives'];
			if($model->save())
				$this->redirect(array('view','id'=>$model->id));
		}

		$this->render('update',array(
			'model'=>$model,
		));
	}

	/**
	 * Deletes a particular model.
	 * If deletion is successful, the browser will be redirected to the 'admin' page.
	 * @param integer $id the ID of the model to be deleted
	 */
	public function actionDelete($id)
	{
		if(Yii::app()->request->isPostRequest)
		{
			// we only allow deletion via POST request
			$this->loadModel($id)->delete();
			
			try{
				$sql = "DELETE * FROM content_point WHERE content_id=$id AND content_type='Creatives';"; 
				$command = Yii::app()->db->createCommand($sql);   
				$data=$command->execute(); 
			}catch(Exception $ex){echo $ex->getMessage();}

			// if AJAX request (triggered by deletion via admin grid view), we should not redirect the browser
			if(!isset($_GET['ajax']))
				$this->redirect(isset($_POST['returnUrl']) ? $_POST['returnUrl'] : array('admin'));
		}
		else
			throw new CHttpException(400,'Invalid request. Please do not repeat this request again.');
	}
	
	// add creative to favorites
	public function actionAddFavCrea($id)
	{	
	
		$condition = "";
		$dataProvider=new CActiveDataProvider('ContentTypes', array(
			'criteria'=>array(
			'condition'=>$condition,
			'order'=>'rand()',
			),
			'pagination' => array('pageSize' => 4,),
			'totalItemCount' => 4,

			
		));
	
		$model=$this->loadModel($id);
		$uid=Yii::app()->user->id;
		$type=1;
		try{
			$sql = "INSERT INTO favourites (user_id, creative_id, type) VALUES ($uid,'$id','$type')"; 
			$command = Yii::app()->db->createCommand($sql);   
			$data=$command->execute(); 
			}catch(Exception $ex){echo $ex->getMessage();}
			
		$points = SiteController::actionAddPoints('other', 'Creatives', "$model->id", "$model->type");	
		
		$this->render('view',array(
			'model'=>$model,
			'dataprovider'=>$dataProvider,
			)
		);	
	}
	
	// delete creative from favorites
	public function actionDelFavCrea($id)
	{	
		$condition = "";
		$dataProvider=new CActiveDataProvider('ContentTypes', array(
			'criteria'=>array(
			'condition'=>$condition,
			'order'=>'rand()',
			),
			'pagination' => array('pageSize' => 4,),
			'totalItemCount' => 4,
		));
	
		$model=$this->loadModel($id);
		$uid=Yii::app()->user->id;
		$type=1;
		//delete from favs
		try{
			$sql = "DELETE FROM favourites WHERE user_id=$uid AND creative_id=$id AND type=$type"; 
			$command = Yii::app()->db->createCommand($sql);   
			$data=$command->execute(); 
			}catch(Exception $ex){echo $ex->getMessage();}
		
		$points = SiteController::actionDelPoints('other', 'Creatives', "$model->id", "$model->type");	
		
		$this->render('view',array(
			'model'=>$model,
			'dataprovider'=>$dataProvider,
			)
		);	
	}
	
	
	// delete user from favorites
	public function actionDelFavUsr($id)
	{	
	
		$condition = "";
		$dataProvider=new CActiveDataProvider('ContentTypes', array(
			'criteria'=>array(
			'condition'=>$condition,
			'order'=>'rand()',
			),
			'pagination' => array('pageSize' => 4,),
			'totalItemCount' => 4,

			
		));
	
	
		$model=$this->loadModel($id);
		$subid=$model->creator_id;
		$uid=Yii::app()->user->id;
		$type=2;
		try{
			$sql = "DELETE FROM favourites WHERE user_id=$uid AND subuser_id=$subid AND type=$type"; 
			$command = Yii::app()->db->createCommand($sql);   
			$data=$command->execute(); 
			}catch(Exception $ex){echo $ex->getMessage();}
		
		$this->render('view',array(
			'model'=>$model,
			'dataprovider'=>$dataProvider,
			)
		);	
	}
	
	// add user to favorites
	public function actionAddFavUsr($id)
	{	
	
		$condition = "";
		$dataProvider=new CActiveDataProvider('ContentTypes', array(
			'criteria'=>array(
			'condition'=>$condition,
			'order'=>'rand()',
			),
			'pagination' => array('pageSize' => 4,),
			'totalItemCount' => 4,

		));
	
		$model=$this->loadModel($id);
		$subid=$model->creator_id;
		$uid=Yii::app()->user->id;
		$type=2;
		try{
			$sql = "INSERT INTO favourites (user_id, subuser_id, type) VALUES ($uid,'$subid','$type')"; 
			$command = Yii::app()->db->createCommand($sql);   
			$data=$command->execute(); 
			}catch(Exception $ex){echo $ex->getMessage();}
		
		$this->render('view',array(
			'model'=>$model,
			'dataprovider'=>$dataProvider,
			)
		);	
	}
	
	
	//List all content point values
	public function actionAllContentsPoints()
	{
				
		$dataProvider = new CActiveDataProvider('ContentPoints', array(
        'pagination'=>array(
                'pageSize'=>10,
				),
		));
		
		$this->render('index_points',array(
			'dataProvider'=>$dataProvider,
		));
	}
	
	// show actual content point value
	public function actionActualContentInfos($id)
	{
		//actual point value
		$condition = "content_id = $id";
		$dataProvider = new CActiveDataProvider('ContentPoints', array(  // todo change to a new view
        'pagination'=>array(
                'pageSize'=>10,
				),
		'criteria'=>array(
			'condition'=>$condition,
		),
		));
		
		
		//list of useres who add this content as a favorite 
		$condition = "id = $id";
		$dataProvider2 = new CActiveDataProvider('FavCreatives', array(
        'pagination'=>array(
                'pageSize'=>10,
				),
		'criteria'=>array(
			'condition'=>$condition,
		),
		));
		
		$this->render('index_infos',array(
			'dataProvider'=>$dataProvider,
			'dataProvider2'=>$dataProvider2,
		));
	}
	
	
	/**
	 * Lists all models.
	 */
	public function actionIndex()
	{
		$dataProvider = new CActiveDataProvider('Creatives', array(
        'pagination'=>array(
                'pageSize'=>10,
        ),
		));
		$this->render('index',array(
			'dataProvider'=>$dataProvider,
		));
	}
	
	public function actionIndexFavCrea()
	{
		$uid=Yii::app()->user->id;
		$condition = "user_id=$uid AND type=1";
		//$condition='creator_id=1';
		
		$dataProvider=new CActiveDataProvider('FavCreatives', array(
			'criteria'=>array(
			'condition'=>$condition,
		),
		));
		$this->render('indexfavcrea',array(
			'dataProvider'=>$dataProvider,)
		);	
	}
	
	public function actionIndexFavUsr()
	{
		$uid=Yii::app()->user->id;
		$condition = "user_id=$uid AND type=2";
		$dataProvider=new CActiveDataProvider('FavUsers', array(
			'criteria'=>array(
			'condition'=>$condition,
		),
		));
		$this->render('indexfavusr',array(
			'dataProvider'=>$dataProvider,)
		);	
	}
	
	public function actionIndexAllFav()
	{
		$uid=Yii::app()->user->id;
		$condition = "user_id=$uid AND type=2";
		$dataProvider_usr=new CActiveDataProvider('FavUsers', array(
			'pagination'=>array(
                'pageSize'=>10,
			),
			'criteria'=>array(
			'condition'=>$condition,
		),
		));
		$condition = "user_id=$uid AND type=1";
		$dataProvider_crea=new CActiveDataProvider('FavCreatives', array(
			 'pagination'=>array(
                'pageSize'=>10,
			),
			'criteria'=>array(
			'condition'=>$condition,
		),
		));
		
		
		$this->render('indexallfav',array(
			'dataProvider_usr'=>$dataProvider_usr,
			'dataProvider_crea'=>$dataProvider_crea,)
		);	
	}
	

	/**
	 * Manages all models.
	 */
	public function actionAdmin()
	{
		$model=new Creatives('search');
		$model->unsetAttributes();  // clear any default values
		if(isset($_GET['Creatives']))
			$model->attributes=$_GET['Creatives'];

		$this->render('admin',array(
			'model'=>$model,
		));
	}

	/**
	 * Returns the data model based on the primary key given in the GET variable.
	 * If the data model is not found, an HTTP exception will be raised.
	 * @param integer the ID of the model to be loaded
	 */
	public function loadModel($id)
	{
		$model=Creatives::model()->findByPk($id);
		if($model===null)
			throw new CHttpException(404,'The requested page does not exist.');
		return $model;
	}

	/**
	 * Performs the AJAX validation.
	 * @param CModel the model to be validated
	 */
	protected function performAjaxValidation($model)
	{
		if(isset($_POST['ajax']) && $_POST['ajax']==='creatives-form')
		{
			echo CActiveForm::validate($model);
			Yii::app()->end();
		}
	}
}
